package com.css.contentcenter.study.config;

import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.alibaba.nacos.client.naming.core.Balancer;
import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.AbstractLoadBalancerRule;
import com.netflix.loadbalancer.BaseLoadBalancer;
import com.netflix.loadbalancer.ILoadBalancer;
import com.netflix.loadbalancer.Server;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.alibaba.nacos.NacosDiscoveryProperties;
import org.springframework.cloud.alibaba.nacos.ribbon.NacosServer;
import org.springframework.util.CollectionUtils;
import sun.text.CollatorUtilities;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

public class NacosSameClusterWeightedRule extends AbstractLoadBalancerRule {
    @Autowired
    private NacosDiscoveryProperties nacosDiscoveryProperties;

    @Override
    public void initWithNiwsConfig(IClientConfig iClientConfig) {

    }

    @Override
    public Server choose(Object o) {
        try {
            BaseLoadBalancer loadBalancer = (BaseLoadBalancer) this.getLoadBalancer();
            String name = loadBalancer.getName();
            //拿到配置文件中的 集群名称
            String clusterName = nacosDiscoveryProperties.getClusterName();
            NamingService namingService = nacosDiscoveryProperties.namingServiceInstance();
            List<Instance> instances = namingService.selectInstances(name, true);
            List<Instance> sameClusterNames = instances
                    .stream()
                    .filter(value -> Objects.equals(clusterName, value.getClusterName())).collect(Collectors.toList());
            List<Instance> instanceListA = new ArrayList<>();

            if (CollectionUtils.isEmpty(sameClusterNames)) {
                instanceListA = instances;
            } else {
                instanceListA = sameClusterNames;
            }
            return new NacosServer(ExtendBalancer.getHostByRandomWeight2(instanceListA));
        } catch (NacosException e) {
            e.printStackTrace();
            return null;
        }
    }
}

class ExtendBalancer extends Balancer {
    public static Instance getHostByRandomWeight2(List<Instance> instances) {
        return getHostByRandomWeight(
                instances
        );
    }
}